package net.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class test8_reptile {
    public static void main(String[] args) {
        String urlToRead = "http://www.jd.com"; //
        System.out.println("Fetching content from: " + urlToRead);
        try {
            URL url = new URL(urlToRead);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 设置合适的超时，防止无限等待
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);

            boolean redirect = false;

            // 检查是否需要重定向
            int status = conn.getResponseCode();
            if (status != HttpURLConnection.HTTP_OK) {
                if (status == HttpURLConnection.HTTP_MOVED_TEMP
                        || status == HttpURLConnection.HTTP_MOVED_PERM
                        || status == HttpURLConnection.HTTP_SEE_OTHER) {
                    redirect = true;
                }
            }

            System.out.println("Response Code: " + status);

            if (redirect) {
                // 获取重定向的 URL 从响应头中
                String newUrl = conn.getHeaderField("Location");
                System.out.println("Redirect to URL : " + newUrl);

                // 重新打开连接到新的 URL
                url = new URL(newUrl);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            // 打印获取到的网页源码
            System.out.println("Content:\n" + content.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
